package leet.ku._160;

class ListNode {
	int val;
	ListNode next;

	ListNode(int x) {
		val = x;
		next = null;
	}
}

public class Solution {
	public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
		if (headA == null || headB == null)
			return null;
		ListNode p1 = headA;
		ListNode p2 = headB;
		while (p1.next != null && p2.next != null) {
			p1 = p1.next;
			p2 = p2.next;
		}
		ListNode p3 = headA;
		ListNode p4 = headB;
		while (p1.next != null) {
			p1 = p1.next;
			p3 = p3.next;
		}
		while (p2.next != null) {
			p2 = p2.next;
			p4 = p4.next;
		}
		if (p1 != p2)
			return null;
		while (p3 != p4) {
			p3 = p3.next;
			p4 = p4.next;
		}
		return p3;
	}
}